﻿using System;
using System.Windows;
using System.Windows.Controls;
using MovieBuddy.Helpers;
using MovieModel.Model.Common;

namespace MovieBuddy.Views.ItemListView
{
    public class ItemListItem<T> : UserControl where T : MovieItem<T>, new()
    {
        public readonly T Item;
        private TextBlock title;
        private readonly EventHandler<ItemUpdatedEventArgs<MovieItem<T>>> itemUpdateHandler;
        private readonly Grid grid = new Grid();

        public ItemListItem(MovieItem<T> item)
        {
            Item = (T)item;
            InitializeComponent();
            itemUpdateHandler = ItemUpdated;
            Unloaded += (s, e) => Item.ItemUpdated -= itemUpdateHandler;
            item.ItemUpdated += itemUpdateHandler;
        }

        void ItemUpdated(object sender, ItemUpdatedEventArgs<MovieItem<T>> e)
        {
            Dispatcher.Invoke(DoLayout);
        }

        private void InitializeComponent()
        {
            AddChild(grid);
            DoLayout();
        }

        private void DoLayout()
        {
            grid.Children.Clear();
            title = new TextBlock
            {
                Height = 45,
                Text = Item.Name,
                VerticalAlignment = VerticalAlignment.Center,
                FontSize = 20,
                TextTrimming = TextTrimming.CharacterEllipsis
            };

            var imageItem = Item as ImageMovieItem<T>;
            if (imageItem != null)
            {
                if (imageItem.ThumbnailLocation != null)
                {
                    var image = new Image();
                    var pic = ImageCache.GetImage(imageItem.ThumbnailLocation);
                    image.Source = pic;
                    image.Height = 45;

                    double aspectRatio = pic.Width/pic.Height;
                    image.Width = (int) (image.Height*aspectRatio);

                    image.HorizontalAlignment = HorizontalAlignment.Left;
                    image.VerticalAlignment = VerticalAlignment.Center;
                    grid.Children.Insert(0, image);
                    var margin = title.Margin;
                    margin.Left = image.Width + 4;
                    title.Margin = margin;
                }
            }

            grid.Children.Add(title);
        }
    }
}
